package com.mm.ai.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.core.io.ByteArrayResource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author： tzy
 * @Date： 2024/11/13 22:27
 */
public class QrCodeGeneratorUtil {
    public static byte[] generateQrCode(String uuid) {
        String qrCodeUrl = "https://login.weixin.qq.com/l/" + uuid;
        int width = 400;
        int height = 400;
        String filePath = "qrcode.png";

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        byte[] bytes = null;
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeUrl, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 创建字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            bytes = baos.toByteArray();
            // 返回响应

            /*             Path path = FileSystems.getDefault().getPath(filePath);
           MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
            System.out.println("QR Code generated at: " + filePath);*/
/*             将二维码转换为ASCII艺术图并输出
            printAsciiArt(bitMatrix, 40, 10);*/
        } catch (Exception e) {
            System.err.println("Error generating QR Code: " + e.getMessage());
        }
        return bytes;
    }


/*    private static void printAsciiArt(BitMatrix bitMatrix, int width, int height) {
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (bitMatrix.get(x * (bitMatrix.getWidth() / width), y * (bitMatrix.getHeight() / height))) {
                    System.out.print("█"); // 使用字符表示黑色部分
                } else {
                    System.out.print(" "); // 使用空格表示白色部分
                }
            }
            System.out.println();
        }
    }*/
}
